﻿/*
 * ========================================================================
 * Copyright(c) 2007-2012 情留メ蚊子, All Rights Reserved.
 * Welcom use the LiteFetion.
 * See more information,Please goto http://www.94qing.com
 * ========================================================================
 * 
 * 作 者：情留メ蚊子
 * Q  Q: 540644769
 * 邮 箱：qlwz@qq.com
 * 网 址：http://www.94qing.com
 * ========================================================================
*/
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using LiteFetion.Model;
using LiteFetion.Utils;
using Newtonsoft.Json.Linq;

namespace LiteFetion
{
    /// <summary>
    /// 消息管理
    /// </summary>
    public class MessageManager
    {
        public MessageManager(FetionClient client)
        {
            FetionClient = client;
        }

        /// <summary>
        /// FetionClient
        /// </summary>
        public FetionClient FetionClient { get; private set; }

        /// <summary>
        /// User
        /// </summary>
        public User User { get { return FetionClient.User; } }

        /// <summary>
        /// 给自己发送短信
        /// </summary>
        /// <param name="message">消息内容</param>
        /// <returns></returns>
        public ActionResult SendSelfSM(string message)
        {
            return this.SendMessage(this.User, message, true);
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="buddy">好友对象</param>
        /// <param name="message">消息内容</param>
        /// <param name="isSendSMS">是否发送短信</param>
        /// <returns></returns>
        public ActionResult SendMessage(Buddy buddy, string message, bool isSendSMS)
        {
            if (buddy == null || message.IsEmpty())
            {
                return ActionResult.WRONG_PARAM;
            }
            string postData = string.Format("ssid={0}&To={1}&msg={2}&IsSendSms={3}",
                this.User.SessionId, buddy.UserId, message, isSendSMS ? 1 : 0);
            HttpHelper http = new HttpHelper();
            http.Url = Gobal.WEBIM_URL_SEND_MESSAGE.FormatWith(this.FetionClient.RequestVersion++);
            http.Method = Method.POST;
            http.PostData = postData;
            http.Cookies = this.User.Cookies;
            http.Do();

            this.FetionClient.Debug(http);

            if (http.StatusCode != HttpStatusCode.OK)
            {
                return ActionResult.HTTP_FAILED;
            }
            JObject json = Util.GetObjectResult(http.Html);
            if (json == null)
            {
                return ActionResult.JSON_FAILED;
            }
            int status = json.Value<int>("rc");
            if (status != 200)
            {
                return ActionResult.REQUEST_FAILED;
            }
            return ActionResult.SUCCESS;
        }

        /// <summary>
        /// 批量发送短信
        /// </summary>
        /// <param name="toBuddies">接受好友的列表，可以包含用户对象</param>
        /// <param name="message">消息内容</param>
        /// <returns></returns>
        public ActionResult BatchSendSMS(List<Buddy> toBuddies, string message)
        {
            if (toBuddies == null || toBuddies.Count == 0 || message.IsEmpty())
            {
                return ActionResult.WRONG_PARAM;
            }
            int count = 0;
            StringBuilder recievers = new StringBuilder();
            foreach (Buddy buddy in toBuddies)
            {
                recievers.Append(buddy.UserId);
                count++;
                if (count < toBuddies.Count)
                {
                    recievers.Append(",");
                }
            }

            string postData = string.Format("ssid={0}&UserName={1}&Message={2}&Receivers={3}",
                this.User.SessionId, this.User.UserId, message, recievers.ToString());
            HttpHelper http = new HttpHelper();
            http.Url = Gobal.WEBIM_URL_SEND_SMS.FormatWith(this.FetionClient.RequestVersion++);
            http.Method = Method.POST;
            http.PostData = postData;
            http.Cookies = this.User.Cookies;
            http.Do();

            this.FetionClient.Debug(http);

            if (http.StatusCode != HttpStatusCode.OK)
            {
                return ActionResult.HTTP_FAILED;
            }
            JObject json = Util.GetObjectResult(http.Html);
            if (json == null)
            {
                return ActionResult.JSON_FAILED;
            }
            int status = json.Value<int>("rc");
            if (status != 200)
            {
                return ActionResult.REQUEST_FAILED;
            }
            return ActionResult.SUCCESS;
        }

        /// <summary>
        /// 发送定时短信
        /// </summary>
        /// <param name="toBuddies">接受好友的列表，可以包含用户对象</param>
        /// <param name="message">消息内容</param>
        /// <param name="minute">多少分钟后发送 必需大于10</param>
        /// <returns></returns>
        public ActionResult SendScheduleSMS(List<Buddy> toBuddies, string message, int minute)
        {
            return SendScheduleSMS(toBuddies, message, DateTime.Now.AddMinutes(minute));
        }

        /// <summary>
        /// 发送定时短信
        /// </summary>
        /// <param name="toBuddies">接受好友的列表，可以包含用户对象</param>
        /// <param name="message">消息内容</param>
        /// <param name="sendDate">发送的时间，最短时间是 当前时间+11分钟-一年后当前时间,否则返回错误</param>
        /// <returns></returns>
        public ActionResult SendScheduleSMS(List<Buddy> toBuddies, string message, DateTime sendDate)
        {
            if (toBuddies == null || toBuddies.Count == 0 || message.IsEmpty())
            {
                return ActionResult.WRONG_PARAM;
            }

            //检查定时短信的定时时间，最短时间是 当前时间+11分钟-一年后当前时间
            //比如当前时间是 2007.7.1 22:56 有效的时间是 2010.7.1 23:07 - 2011.7.1 22:56，在这个时间之内的才是有效时间，
            if (DateTime.Compare(sendDate, DateTime.Now.AddMinutes(11)) < 0)
            {
                return ActionResult.WRONG_PARAM;
            }
            if (DateTime.Compare(sendDate, DateTime.Now.AddYears(1)) >= 0)
            {
                return ActionResult.WRONG_PARAM;
            }

            int count = 0;
            StringBuilder recievers = new StringBuilder();
            foreach (Buddy buddy in toBuddies)
            {
                recievers.Append(buddy.UserId);
                count++;
                if (count < toBuddies.Count)
                {
                    recievers.Append(",");
                }
            }

            string postData = string.Format("ssid={0}&UserName={1}&Message={2}&Receivers={3}&SendTime={4}",
                this.User.SessionId, this.User.UserId, message, recievers.ToString(), sendDate.AddHours(-8).ToString("yyyy-M-d+H:m:s"));
            HttpHelper http = new HttpHelper();
            http.Url = Gobal.WEBIM_URL_SET_SCHEDULESMS.FormatWith(this.FetionClient.RequestVersion++);
            http.Method = Method.POST;
            http.PostData = postData;
            http.Cookies = this.User.Cookies;
            http.Do();

            this.FetionClient.Debug(http);

            if (http.StatusCode != HttpStatusCode.OK)
            {
                return ActionResult.HTTP_FAILED;
            }
            JObject json = Util.GetObjectResult(http.Html);
            if (json == null)
            {
                return ActionResult.JSON_FAILED;
            }
            int status = json.Value<int>("rc");
            if (status != 200)
            {
                return ActionResult.REQUEST_FAILED;
            }
            return ActionResult.SUCCESS;
        }
    }
}
